package com.to8to.kitt.esb.client;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.thrift.TServiceClient;

import com.to8to.kitt.strategy.SelectorStrategy;

public class ThriftClientPool {

	public Map<String, TServiceClient> clients = new HashMap<String, TServiceClient>();
	
	private SelectorStrategy<Entry<String, TServiceClient>> strategy;
	
	public ThriftClientPool(SelectorStrategy<Entry<String, TServiceClient>> strategy)
	{
		this.strategy = strategy;
	}
	
	public void add(String instance, TServiceClient client)
	{
		clients.put(instance, client);
	}
	
	public void remove(String instance)
	{
		TServiceClient c = clients.get(instance);
		if(c != null)
			c = null;
		clients.remove(instance);
	}
	
	public Entry<String, TServiceClient> get()
	{
		List<Entry<String, TServiceClient>> list = new LinkedList<Entry<String, TServiceClient>>();
		list.addAll(clients.entrySet());
		if(list.isEmpty())
			return null;
		return strategy.select(list);
	}
}
